import stringify from '@/utils/querystring'
import { timeFormat } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
import router from './router'
import cookie from './cookie'
import { PARAMS_KEY } from "@/hooks/useRouter";

/**
 * 未登录无权限
 */
export const handleLoginFailure = () => {
    // todo 添加记录参数逻辑
    // router.replace({
    //   path: '/pages/login/login',
    // })
    const routes = getCurrentPages();
    const curRoute = routes[routes.length - 1];
    if (["pages/login/guid", "pages/login/index"].includes(curRoute.route)) {
        return;
    }
    let fullPath
    // #ifndef MP-WEIXIN
    fullPath = curRoute.$page.fullPath || `/${ curRoute.route }?${ PARAMS_KEY }=${ curRoute.$page.options[PARAMS_KEY] }`
    // #endif
    // #ifdef MP-WEIXIN
    fullPath = `/${ curRoute.route }?${ PARAMS_KEY }=${ curRoute.options[PARAMS_KEY] }`
    // #endif
    console.log(curRoute)
    uni.setStorage({
        key: 'lastFullPath',
        data: fullPath
    })
    uni.redirectTo({
        url: '/pages/login/guid',
    })
}

export const afterLogin = () => {
    const tabsList = [
        '/root/goodsCategory/goodsCategory',
        '/root/index/index',
        '/root/shoppingCart/shoppingCart',
        '/root/user/user'
    ]
    const lastPath = uni.getStorageSync('lastFullPath');
    if (lastPath) {
        const str = lastPath.split("?")
        if (tabsList.includes(str[0])) {
            uni.switchTab({url: lastPath})
        } else {
            uni.redirectTo({url: lastPath})
        }
        uni.removeStorageSync('lastFullPath')
    } else {
        uni.switchTab({url: '/root/index/index'})
    }
}

export function parseUrl(location) {
    if (typeof location === 'string') return location
    const {url, query} = location

    const queryStr = stringify(query)

    if (!queryStr) {
        return url
    }

    return `${ url }?${ queryStr }`
}


export function objectURLToBlob(url) {
    return new Promise(resolve => {
        const http = new XMLHttpRequest()
        http.open('GET', url, true)
        http.responseType = 'blob'
        http.onload = function (e) {
            if (this.status == 200 || this.status === 0) {
                resolve(this.response)
            }
        }
        http.send()
    })
}

/**
 * 判断h5环境是否在微信浏览器内
 * @returns {boolean}
 */
export function h5InWeChat() {
    if (!navigator || (navigator && !navigator.userAgent)) return false
    let ua = navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == "micromessenger"
}

export function createMessage(msg, data) {
    return {
        msg,
        data
    }
}


const toAuth = () => {
    uni.showToast({
        title: '暂未开放',
        icon: 'none',
        duration: 2000,
    })
}

export default {
    install: (app, options) => {
        // 在这里编写插件代码
        // 注入一个全局可用的 $translate() 方法
        app.config.globalProperties.$yrouter = router
        app.config.globalProperties.$cookie = cookie
        app.config.globalProperties.$toAuth = toAuth
        app.config.globalProperties.$timeFormat = timeFormat
        app.config.globalProperties.$onClickLeft = () => {
            uni.navigateBack()
            // router.back()
        }

        // #ifdef H5
        app.config.globalProperties.$platform = 'h5'
        // #endif

        // #ifdef APP-PLUS
        // app端
        app.config.globalProperties.$platform = 'app'
        // #endif

        // #ifdef MP-WEIXIN
        app.config.globalProperties.$platform = 'routine'
        // #endif
    },
}


// 微信支付环境类型(前端用)
export const WECHAT_PAY_ENV_TYPE = {
    APP: 'app', // APP
    MINI_PROGRAM: 'miniProgram', // 小程序
    H5_IN: 'h5In', // 内H5
    H5_OUT: 'h5Out' // 外H5
}

/**
 * 获取当前支付环境环境
 * @returns {string} WECHAT_PAY_ENV_TYPE
 */
export function getEnvType() {
    let envType; // 0.APP 1.微信小程序 2.微信内H5 3.微信外H5 WechatPayEnvType
    // #ifdef APP-PLUS
    envType = WECHAT_PAY_ENV_TYPE.APP
    // #endif
    // #ifdef MP-WEIXIN
    envType = WECHAT_PAY_ENV_TYPE.MINI_PROGRAM
    // #endif
    // #ifdef H5
    if (h5InWeChat()) {
        envType = WECHAT_PAY_ENV_TYPE.H5_IN
    } else {
        envType = WECHAT_PAY_ENV_TYPE.H5_OUT
    }
    // #endif
    return envType
}

/**
 * 判断是不是图片
 *
 * @param filename 文件名
 * */
export const isImage = (filename) => {
    // 获取文件扩展名
    const extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();

    // 常见图片文件扩展名
    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];

    // 检查文件扩展名是否在图片扩展名数组中
    return imageExtensions.includes(extension);
}


export function parseQuery() {
    let res = {}
  
    // #ifdef H5
    const query = (location.href.split('?')[1] || '').trim().replace(/^(\?|#|&)/, '')
  
    if (!query) {
      return res
    }
  
    query.split('&').forEach(param => {
      const parts = param.replace(/\+/g, ' ').split('=')
      const key = decodeURIComponent(parts.shift())
      const val = parts.length > 0 ? decodeURIComponent(parts.join('=')) : null
  
      if (res[key] === undefined) {
        res[key] = val
      } else if (Array.isArray(res[key])) {
        res[key].push(val)
      } else {
        res[key] = [res[key], val]
      }
    })
    // #endif
    // #ifndef H5
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    res = currentPage.options //如果要获取url中所带的参数可以查看options
    // #endif
  
    return res
  }
  